using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Model.Core.DbContexts;
using Model.Core.Entity;
using Model.Core.Entity.Jwts;
using RobotWebApiService.Models;
using Swashbuckle.AspNetCore.Annotations;

namespace RobotWebApiService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    {
        private readonly MyDbContext _context;

        public UserController(MyDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        [HttpGet]
        [SwaggerResponse(200, Type = typeof(ApiResponse<IEnumerable<User>>))]
        public async Task<ApiResponse<IEnumerable<User>>> GetUsers(int pageNumber = 1, int pageSize = 10)
        {
            try
            {
                var query = _context.User
                    .Where(u => !u.IsDeleted)
                    .OrderBy(u => u.CreatedTime);

                var totalCount = await query.CountAsync();
                var items = await query
                    .Skip((pageNumber - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                return new PagedApiResponse<IEnumerable<User>>(true, "", items, pageNumber, pageSize, totalCount);
            }
            catch (Exception ex)
            {
                return new ApiResponse<IEnumerable<User>>(false, ex.Message);
            }
        }

        /// <summary>
        /// 获取单个用户详情
        /// </summary>
        [HttpGet("{id}")]
        [SwaggerResponse(200, Type = typeof(ApiResponse<User>))]
        [SwaggerResponse(404, Type = typeof(ApiResponse<string>))]
        public async Task<ApiResponse<User>> GetUser(Guid id)
        {
            try
            {
                var user = await _context.User
                    .FirstOrDefaultAsync(u => u.Id == id && !u.IsDeleted);

                return user == null 
                    ? new ApiResponse<User>(false, "用户不存在") 
                    : new ApiResponse<User>(true, "", user);
            }
            catch (Exception ex)
            {
                return new ApiResponse<User>(false, ex.Message);
            }
        }

        /// <summary>
        /// 创建新用户
        /// </summary>
        [HttpPost]
        [SwaggerResponse(201, Type = typeof(ApiResponse<User>))]
        public async Task<ApiResponse<User>> CreateUser([FromBody] User user)
        {
            try
            {
                user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(user.PasswordHash);
                _context.User.Add(user);
                await _context.SaveChangesAsync();
                return new ApiResponse<User>(true, "创建成功", user);
            }
            catch (Exception ex)
            {
                return new ApiResponse<User>(false, ex.Message);
            }
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        [HttpPut("{id}")]
        [SwaggerResponse(200, Type = typeof(ApiResponse<User>))]
        [SwaggerResponse(400, Type = typeof(ApiResponse<string>))]
        public async Task<ApiResponse<User>> UpdateUser(Guid id, [FromBody] User user)
        {
            try
            {
                if (id != user.Id) return new ApiResponse<User>(false, "ID不匹配");

                _context.Entry(user).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return new ApiResponse<User>(true, "更新成功", user);
            }
            catch (Exception ex)
            {
                return new ApiResponse<User>(false, ex.Message);
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        [HttpDelete("{id}")]
        [SwaggerResponse(200, Type = typeof(ApiResponse<string>))]
        [SwaggerResponse(404, Type = typeof(ApiResponse<string>))]
        public async Task<ApiResponse<string>> DeleteUser(Guid id)
        {
            try
            {
                var user = await _context.User.FindAsync(id);
                if (user == null) return new ApiResponse<string>(false, "用户不存在");

                user.IsDeleted = true;
                await _context.SaveChangesAsync();
                return new ApiResponse<string>(true, "删除成功");
            }
            catch (Exception ex)
            {
                return new ApiResponse<string>(false, ex.Message);
            }
        }
    }
}